<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

/**
 * 
 * 管理奖项控制
 * @author alang
 *
 */

class Reward extends Admin_controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('reward_mdl');
		$this->load->library('form_validation');
	}
	
	/**
	 * 奖项列表
	 * 
	 */
	public function index()
	{
		/*分页设置*/
		$enabled = intval($this->uri->rsegment(4));
		$page = $this->uri->rsegment(6);
	
		$page = ($page && is_numeric($page)) ? intval($page) : 1;
		$limit = 1000;
		$offset = ($page - 1) * $limit;
		$pagination = '';
	
		$count = $this->reward_mdl->get_reward_count($enabled);
		$this->load->library('pagination');
		$config['base_url'] = base_url().'/adminroot/reward/index/enabled/'.$enabled.'/page/';
		$config['total_rows'] = $count;
		//设置url上第几段用于传递分页器的偏移量
		$config ['uri_segment'] = 7;	 
		$config['per_page'] = $limit; 
		$config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config); 
				
		$data = array();
		$data['list'] = $this->reward_mdl->get_reward_list(true,$limit, $offset,'DESC',$enabled);
		$data['page'] = $this->pagination->create_links();
		$data['enabled'] = $enabled;	
		
		/*奖品*/
		$this->load->model('stock_mdl','stock');
		$stock = $this->stock->getStockhaved();
		$data['stock'] = $stock;
		
		/*参与情况*/	
		$this->load->model('lottery_mdl','lottery');
		$product = $this->lottery->get_lottery_person_product_onther();
		$data['product'] = $product;
		
		/*
		if($enabled > 1){
			
			$this->load->model('lottery_mdl','lottery');
			$product = $this->lottery->get_lottery_person_product_onther();
			$data['product'] = $product;
			
		}
		*/
		$this->load->view('adminroot/list_reward',$data);
	}
	/**
	 * 编辑，更新奖项
	 */
	public function edit_reward()
	{
		$id = intval($this->uri->rsegment(4));

		$this->_load_validation_rules();
		if($this->form_validation->run() == FALSE)
		{
			$data['reward'] = $this->reward_mdl->get_reward_by_id($id);
			$data['productarr'] = explode(',', $data['reward']['products']);
			$this->load->model('product_mdl','product');
			$this->load->model('stock_mdl','stock');
			
			$stock = array();
			$stocks = $this->stock->get_stock_list(false);
			foreach($stocks as $k => $v){
				
					$stock[$v['productid']][] = $v;

			}
			
			$data['stock'] = $stock;
			$data['product'] = $this->product->get_product_list(false);
			$this->load->view('adminroot/edit_reward',$data);
		}
		else 
		{
			
			$maxnumber = intval($this->input->post('maxnumber'));
			$minnumber = 1;
			if($maxnumber < $minnumber){
				exit('自大数小于最小数');
			}
			for($i=$minnumber;$i<=$maxnumber;$i++){
				$rewardarr[] = $i;
			}
			
			//保存号码副本
			$rewardstr = implode(',', $rewardarr);
			$rnum = count($rewardarr);
			$data['rnum'] = $rnum;
			$data['rewardnum'] = $rewardstr;
			
			//奖品
			$parr = $this->input->post('product');
			if(count($parr))
			{
				$pstr = implode(',', $parr);
				$data['products'] = $pstr;
			}
			else 
			{
				$pstr = '';
			}
			
			//概率
			$probability =ceil((count($parr)/$rnum)*100);
			//图片修改
			$updata = array();
			if(!empty($_FILES['rewardpic']['name'])){
				
				$config['upload_path'] = './upload/reward/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['encrypt_name'] = true;
				$config['overwrite'] = false;
			  	$this->load->library('upload', $config);
 
				  if ( ! $this->upload->do_upload('rewardpic'))
				  {
				   $error = array('error' => $this->upload->display_errors());
				  	var_dump($error);
				  }
				  $updata = $this->upload->data();
			}
			else {
				$updata['file_name'] = $this->input->post('rewardpicold');
			}
			
			$result = $this->reward_mdl->update_reward(
				intval($this->input->post('id')),
				array(
					'infos' => $this->input->post('infos'),
					'prices' =>  $this->input->post('prices'),
					'products' => $this->input->post('products'),
					'rewardpic' => $updata['file_name'],
					'singleprice' => $this->input->post('singleprice'),
					'probability' => $probability,
					'enabled' => $this->input->post('enabled'),
					'showtype' => $this->input->post('showtype'),
					'content' =>$this->input->post('content'),
					'rewardnum' =>$rewardstr,
					'rnum' => $rnum,
					'maxnumber' => $maxnumber,
					'minnumber' => $minnumber,
					'content' => $this->input->post('content'),
					'products' => $pstr,
					'beginDate' => strtotime($this->input->post('beginDate')),
					'endDate' => strtotime($this->input->post('endDate'))
				)
			);
			
			if($result)
			{							
				
				$this->load->model('lottery_mdl','lottery');
				$this->load->model( 'stock_mdl' , 'stock');
							//删除掉原来的号码
				$this->lottery->del_rewardnum_by_rewardid(intval($this->input->post('id')));
				//重置
				$stockdata['rewardid'] = 0;
				$stockdata['used'] = 0;
				$stockconfig['rewardid'] = $this->input->post('id');
				
				$this->stock->setStockNum($stockconfig,$stockdata);
				//添加号码到号码表 
				$this->lottery->set_lottery_nums($this->input->post('id'),$rewardarr);
				
				if(count($parr))
				{
					//随机产生中奖的号码
					$lottery_rand = $this->getlotteryrand($rewardarr,count($parr));
					//把产生的随机中奖号码赋到奖品上
					foreach ($lottery_rand as $k =>$v2)
					{
		
						$data2['rewardid'] = $this->input->post('id');
						$data2['used'] = 1;
						
						$config = array(
							'productid' => $parr[$k],
							'rewardid <' => 1
						);	
										
						$this->stock->getStockByOne($parr[$k],$data2,$config);
					}
					
					//给中奖号码添加奖品
					$stock = $this->stock->getStockByRewardid($this->input->post('id'));
					foreach ($lottery_rand as $k3 =>$v3)
					{
						$this->lottery->set_lottery_rand($this->input->post('id'),$v3,$parr[$k3],$stock[$k3]['id']);			
					}
				}

			}
			else 
			{
				echo 'error';
			}

			redirect('/adminroot/reward/index');

		}
		
		
	}
	
	/**
	 * 添加奖项
	 * 
	 */
	
	public function addreward()
	{
		
		$this->_load_validation_rules();
		if($this->form_validation->run() == FALSE)
		{
			
			$this->load->model('product_mdl','product');
			$this->load->model('stock_mdl','stock');
			$data['product'] = $this->product->get_product_list(false);
			$stock = array();
			$stocks = $this->stock->get_stock_list(false);
			foreach($stocks as $k => $v){
				if(empty($v['rewardid'])){
					$stock[$v['productid']][] = $v;
				}
			}
			
			$data['stock'] = $stock;
			$this->load->view('adminroot/add_reward',$data);
			
		}
		else 
		{
			$updata = array();
			//判断是否有图片上传
			if(!empty($_FILES['rewardpic'])){
				
				$config['upload_path'] = './upload/reward/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['encrypt_name'] = true;
				$config['overwrite'] = false;
			  	$this->load->library('upload', $config);
 
				  if ( ! $this->upload->do_upload('rewardpic'))
				  {
				   $error = array('error' => $this->upload->display_errors());
				  	var_dump($error);
				  }
				  $updata = $this->upload->data();
			}
			
			$data['infos'] = $this->input->post('infos');
			$data['prices'] = $this->input->post('prices');
			$data['singleprice'] = $this->input->post('singleprice');
			$data['enabled'] = $this->input->post('enabled');
			$data['rewardpic'] = $updata['file_name'];
			$data['content'] = $this->input->post('content');
			$data['showtype'] = $this->input->post('showtype');	
			$data['maxnumber'] = $this->input->post('maxnumber');
			$data['minnumber'] = $this->input->post('minnumber');
			$data['beginDate'] = strtotime($this->input->post('beginDate'));
			$data['endDate'] = strtotime($this->input->post('endDate'));
			$rewardstr = $this->input->post('rewardnum');
			
			//保存号码副本=====================================
			$maxnumber = intval($this->input->post('maxnumber'));
			$minnumber = 1;
			if($maxnumber < $minnumber){
				exit('自大数小于最小数');
			}
			for( $i=$minnumber; $i<=$maxnumber; $i++ ){
				$rewardarr[] = $i;
			}			
			
			$rewardstr = implode( ',', $rewardarr );
			$rnum = count($rewardarr);
			$data['rnum'] = $rnum;
			$data['rewardnum'] = $rewardstr;
			
			//产品========================================
			$parr = $this->input->post('product');
			if(count($rewardarr) < count($parr)){	
				exit('error');
			}
			if(count($parr))
			{
				$pstr = implode(',', $parr);
				$data['products'] = $pstr;
			}
			else
			{
				$pstr = '';
			}
				
			//概率
			$data['probability'] = ceil((count($parr)/$rnum)*100);
			//入库
			$result = $this->reward_mdl->add_reward($data);
			if($result)
			{							
				
				$this->load->model('lottery_mdl','lottery');
				$this->load->model( 'stock_mdl' , 'stock');
				
				//添加号码到号码表 
				$this->lottery->set_lottery_nums($result,$rewardarr);
				
				if(count($parr))
				{
					//随机产生中奖的号码
					$lottery_rand = $this->getlotteryrand(count($rewardarr),count($parr));

					//把产生的随机中奖号码赋到奖品上
					foreach ($lottery_rand as $k =>$v2)
					{
		
						$data2['rewardid'] = $result;
						$data2['used'] = 1;
						
						$config = array(
							'productid' => $parr[$k],
							'rewardid <' => 1
						);	
										
						$this->stock->getStockByOne($parr[$k],$data2,$config);
					}
					
					//给中奖号码添加奖品
					$stock = $this->stock->getStockByRewardid($result);
					foreach ( $lottery_rand as $k3 =>$v3 )
					{
						$this->lottery->set_lottery_rand($result,$v3,$stock[$k3]['productid'],$stock[$k3]['id']);			
					}
				}
			}
			else 
			{
				echo 'error';
			}
			redirect('adminroot/reward');
		}
		
	}
	
	/**
	 * 删除奖项
	 * 
	 */
	public function del_reward()
	{
		$id = intval($this->uri->rsegment(4));
		$result = $this->reward_mdl->del_reward($id);	
		$this->load->model('stock_mdl','stock');	
		//delete lottery
		$this->load->model('lottery_mdl','lottery');
		$lottery = $this->lottery->del_rewardnum_by_rewardid($id);
		//重置
		$stockdata['rewardid'] = 0;
		$stockdata['used'] = 0;
		$stockconfig['rewardid'] = $id;
		$this->stock->setStockNum($stockconfig,$stockdata);
		
		redirect('adminroot/reward');
	}
	
	
	private function _load_validation_rules()
	{
		$this->form_validation->set_error_delimiters('<li>', '</li>');
		$this->form_validation->set_rules('infos','活动信息','required|xss_clean');
		$this->form_validation->set_rules('prices','中奖金额','required');
		$this->form_validation->set_rules('product','奖品','required');
		$this->form_validation->set_rules('singleprice','单位金额','required');
		$this->form_validation->set_rules('maxnumber','最大可选数字');
	}
	
	private function getlotteryrand($end, $limit)
	{
		$rand_array=range(1,$end); 
		shuffle($rand_array);//调用现成的数组随机排列函数 
		return array_slice($rand_array,0,$limit);//截取前$limit个 
	}
	
	
	public function changestatic()
	{
		$id = intval($this->uri->rsegment(4));
		$stat = intval($this->uri->rsegment(6));
		if(empty($id) && empty($stat))
		{
			exit('id and stat empty');
		}
		

		if($stat == 2){
			$data = array(
				'enabled' => $stat,
				'endDate2' => time(),
				'endDate' => time(),
			);
		}else{
			$data = array(
				'enabled' => $stat,
				'beginDate' => time()
			);
		}
		 $this->reward_mdl->update_reward($id,$data);
		 redirect('adminroot/reward');
	}
	
}